package com.openroom.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

public class EventManager {

	private static final Logger LOGGER = Logger.getLogger(EventManager.class);

	private static HashMap<EventType, List<EventHandler>> handlers = new HashMap<EventType, List<EventHandler>>();

	private static EventManager instance = new EventManager();

	private EventManager() {
	}

	public static EventManager getInstance() {
		return instance;
	}

	public void publishEvent(ApplicationEvent event) {
		List<EventHandler> list = getHandlers().get(event.getType());
		if (list != null)
			try {
				LOGGER.debug(list.size() +" handlers registered for event: " + event.getType());
				for (EventHandler eventHandler : list) {
					long start = System.nanoTime();
					eventHandler.handle(event);
					LOGGER.trace("EventManager.publishEvent() handler:"
							+ eventHandler.getClass() + " finished in "
							+ (System.nanoTime() - start) / 1000 + " ms for event:" + event.getType());
				}
			} catch (Exception e) {
				LOGGER.error(event.getType());
				LOGGER.error("error",e);
			}
	}

	public void listenToEventType(EventType eventType, EventHandler eventHandler) {
		List<EventHandler> list = getHandlers().get(eventType);
		if (list == null) {
			list = new ArrayList<EventHandler>();
		}
		list.add(eventHandler);
		getHandlers().put(eventType, list);
	}

	public void listenToEventType(EventHandler eventHandler,
			EventType... eventType) {
		for (EventType evt : eventType) {
			listenToEventType(evt, eventHandler);
		}
	}

	public static HashMap<EventType, List<EventHandler>> getHandlers() {
		return handlers;
	}
}
